package com.idanchuang.component.consumer.ribbon;

import com.idanchuang.component.consumer.config.RibbonResolveMapConfig;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author yjy
 * @date 2019/12/25 18:02
 **/
public class DirectResolveRule extends AbstractLoadBalancerRule {

    private static final Logger logger = LoggerFactory.getLogger(DirectResolveRule.class);

    private final RibbonResolveMapConfig ribbonResolveMapConfig;

    public DirectResolveRule(RibbonResolveMapConfig ribbonResolveMapConfig) {
        this.ribbonResolveMapConfig = ribbonResolveMapConfig;
    }

    @Override
    public Server choose(Object key) {
        ILoadBalancer lb = getLoadBalancer();
        if (lb == null) {
            logger.warn("no load balancer");
            return null;
        }
        Server server = null;
        if (ribbonResolveMapConfig.isEnabled() && lb instanceof BaseLoadBalancer) {
            String serviceName = ((BaseLoadBalancer) lb).getName();
            Map<String, String> servers = ribbonResolveMapConfig.getDirectServers();
            server = chooseFrom(servers, serviceName);
            if (server == null) {
                server = chooseFrom(ribbonResolveMapConfig.getServers(), serviceName);
            }
        }
        return server;
    }

    private Server chooseFrom(Map<String, String> servers, String serviceName) {
        for (String k : servers.keySet()) {
            if (k.equalsIgnoreCase(serviceName)) {
                String[] address = servers.get(k).split(":");
                int port = address.length == 1 ? 80 : Integer.parseInt(address[1]);
                Server server = new Server(address[0], port);
                server.setReadyToServe(true);
                server.setAlive(true);
                if (ribbonResolveMapConfig.isLogChooseServer()) {
                    logger.info("Choose direct resolve service provider [{}] > [{}]", serviceName, server);
                }
                return server;
            }
        }
        return null;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }
}